#!/usr/bin/env bash
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
# Function :
# Platform :
# Version  :1.02
# Date     :2023-03-30
# Author   :mugoLH
# Contact  :hxsaj@126.com
# Company  :
# depend on:
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
#  函数列表 Function list
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
info_p(){  printf "\e[1;32;40m%-12s\e[0m %-1s\n\e[0m" "${1}" "${2}"  >&1 ;}
tips_p(){  printf "\e[1;36;40m%-5s\e[0m %-1s\n\e[0m"  "${1}" "${2}"  >&1 ;}
error_p(){ printf "\e[1;35;40m%-12s\e[0m %-1s\n\e[0m" "${1}" "${2}"  >&1 ;}

#  变量列表 Variable list
DEFAULTS_HOST_FILE=./server

#  IP检查合法性
check_ip() {
    IP=$1
    if [[ $IP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        FIELD1=$(echo $IP|cut -d. -f1)
        FIELD2=$(echo $IP|cut -d. -f2)
        FIELD3=$(echo $IP|cut -d. -f3)
        FIELD4=$(echo $IP|cut -d. -f4)
        if [ $FIELD1 -le 255 -a $FIELD2 -le 255 -a $FIELD3 -le 255 -a $FIELD4 -le 255 ]; then
            echo "ok"
        else
            echo "no"
        fi
    else
        echo "error"
    fi
}

#  检查登录  
check_lonin(){
	if [ $# -eq 1 ];then
		# 如果只有一个参数
		# 检查参数是否为合法的IP
		if [[ $(check_ip "${1}") = "ok" ]];then
			ssh root@${1}
		# 检查参数是否在主机清单文件中存在
		elif [[ -n $(egrep -v "^$|^#" ${HOST_FILE} | grep ${1}) ]] ;then
			if [ $(egrep -v "^$|^#" ${HOST_FILE} | grep -w "${1}" |sort | uniq | awk '{print NF}') -ne 6 ];then
				host_h=$(egrep -v "^$|^#" ${HOST_FILE} | awk "/${1}/{print\$1}")
				ssh root@${host_h}
			else
				user_h=$(egrep -v "^$|^#" ${HOST_FILE} | awk "/${1}/{print\$5}")
				port_h=$(egrep -v "^$|^#" ${HOST_FILE} | awk "/${1}/{print\$6}")
				host_h=$(egrep -v "^$|^#" ${HOST_FILE} | awk "/${1}/{print\$1}")
				ssh -p ${port_h} ${user_h}@${host_h}
			fi
		# 参数不是合法ip，也不在主机清单中，就报错
		else
			error_p "[ ERROR ]:" "输入主机或IP错误！"
		fi
	elif [ $# -eq 0 ];then
		#  无参数的情况：直接打印可以登录的服务器
		clear && print_host ${HOST_FILE}
	else
		error_p "[ ERROR ]:" "只接受 0-1个参数，参数为需要连接的【 主机名 | IP | 缩写 】"
	fi
}


#  打印可登录的服务器，输入 q 或者 Q 退出选择
print_host(){
	HOST_FILE=${1}
	if [ ! -f ${HOST_FILE} ];then
		error_p "[ WARNING ]:" "不存在主机文件 ${HOST_FILE}，请检查！"
		return $?
	fi
	egrep -v "^$|^#" ${HOST_FILE} |awk '{print$1,$2,$3,$4}' |awk '$0=NR") "$0' |\
	awk '
	BEGIN{
		print  "  --------------------------------------------------------------------------------------------------";
		printf "  | %-2s | %-14s| %-18s| %-34s| %-20s|\n","序号","IP","主机名","角色/说明","地域/机房/局点" ;
		print  "  --------------------------------------------------------------------------------------------------";
	}
	{
		printf "     %-4s %-14s %-20s %-34s %-20s\n",$1,$2,$3,$4,$5;
    }
    END{
    	print "  --------------------------------------------------------------------------------------------------";
    }'

	# 获取主机个数
	hosts_nu=$(egrep -v "^$|^#" ${HOST_FILE} | wc -l)

	# 选择登录的主机
	read -t 30 -p  "  选择需要登录的服务器[默认为 1]：" Choices_Server

	if [ ! ${Choices_Server} ];then
		Choices_Server=1
	fi

	#  判断输入的合法性（必须是数字，并且是主机个数之内）
	if echo ${Choices_Server} |grep -q "^[0-9]" ;then
		if [ ${Choices_Server} -le ${hosts_nu} ] && [ ${Choices_Server} -gt 0 ];then
			if [ $(egrep -v "^$|^#" ${HOST_FILE} | sed -n "${Choices_Server}p" | awk '{print NF}') -ne 6 ];then
				host_h=$(egrep -v "^$|^#" ${HOST_FILE} | sed -n "${Choices_Server}p" | awk '{print$1}')
				ssh ${host_h}
			else
				user_h=$(egrep -v "^$|^#" ${HOST_FILE} | sed -n "${Choices_Server}p" | awk '{print$5}')
				port_h=$(egrep -v "^$|^#" ${HOST_FILE} | sed -n "${Choices_Server}p" | awk '{print$6}')
				host_h=$(egrep -v "^$|^#" ${HOST_FILE} | sed -n "${Choices_Server}p" | awk '{print$1}')
				ssh -p ${port_h} ${user_h}@${host_h}
			fi
		else
			clear && error_p "[ WARNING ]:" "服务器序号选择错误，请重新选择："
			print_host ${HOST_FILE}
		fi
	elif [[ ${Choices_Server} == "q" ]] || [[ ${Choices_Server} == "Q" ]] ; then
		exit
	else
		clear && error_p "[ WARNING ]:" "请输入服务器序号："
		print_host ${HOST_FILE}
	fi
}



#  检查参数
if [ $# -eq 0 ];then
	#  无参数的情况：使用默认的主机清单文件打印可以登录的服务器
	if [ -f ${DEFAULTS_HOST_FILE} ];then
		HOST_FILE=${DEFAULTS_HOST_FILE}
		clear && print_host ${HOST_FILE}
	else
		error_p "[ ERROR ]:" "默认主机清单${DEFAULTS_HOST_FILE}不存在"
	fi
else
    #  获取主机组清单
    while [ -n "$1" ]; do
        case $1 in
            -f | --file )
                HOST_FILE="${2}"
                shift 2
                ;;
            *)
                break
                ;;
        esac
    done

    #  指定主机清单文件
    if [[ -f ${HOST_FILE} ]] ;then
    	#  指定主机清单文件，则按指定主机文件执行
    	check_lonin "$@"

    elif [[ ! -f ${HOST_FILE} ]]; then
    	#  没有指定主机清单文件，则按默认主机文件执行
    	HOST_FILE=${DEFAULTS_HOST_FILE}
    	check_lonin "$@"
    fi
fi
